﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ShineTech.Web.Helpers
{
    public class MyActionFilterAttribute : Attribute, IActionFilter
    {
        public void OnActionExecuting(ActionExecutingContext context)
        {
            var controller = context.Controller;
            if (controller == null) return;
            var token = context.HttpContext.GetToken(); 

            var isValid = TokenHelper.Validate(token);
            if (!isValid)
            {
                context.Result = new BadRequestObjectResult("token已失效");
            }
            // do something before the action executes
        }

        public void OnActionExecuted(ActionExecutedContext context)
        {

            // do something after the action executes
        }
    }

    public static class HttpContextEx
    {
        public static string GetToken(this HttpContext httpContext) 
        {
            var token = httpContext.Request.Headers.ContainsKey("Token") ?
                   httpContext.Request.Headers["Token"].ToString() : "";
            return token;

        }

    }
}
